package com.ititer.web.controller;

import java.util.List;

import org.apache.commons.lang.ArrayUtils;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;

import com.ititer.annotation.LoginRequired;
import com.ititer.bean.AccountBean;
import com.ititer.enums.CodeDictionaryTypes;
import com.ititer.model.AccountDomains;
import com.ititer.model.CodeDictionary;
import com.ititer.web.abs.AbstractController;

/**
 * Domain for user.
 * @author aceyin
 *
 */
@Resource
public class Domain extends AbstractController {
	@Get
	@Path("/domain")
	@LoginRequired
	public void domainForm() {
		List<CodeDictionary> domains = codeDictionarySvc.getCodeDictionary(CodeDictionaryTypes.ItDomain.getValue());
		List<AccountDomains> selectedDomain = accountSvc.getDomains(getSession().getId());
		StringBuffer domainNames = new StringBuffer(",");
		for (AccountDomains domain : selectedDomain) {
			domainNames.append(domain.getDomain()).append(",");
		}
		putData("AllDomains", domains);
		putData("SelectedDomains", domainNames);
	}

	@Post
	@Path("/domain")
	@LoginRequired
	public void postDomain(String[] domains) {
		if (ArrayUtils.isEmpty(domains)) {
			setErrorMessage("please.select.domain");
			controllerResult.redirectTo(Domain.class).domainForm();
		} else {
			AccountBean account = new AccountBean();
			account.setId(getSession().getId());
			account.setDomains(domains);
			boolean success = accountSvc.updateDomain(account);
			if (success) {
				controllerResult.redirectTo(My.class).home();
			} else {
				controllerResult.redirectTo(Error.class).info();
			}
		}
	}

	@Get
	@Path("/domains/{userUri}")
	public void listDomain(String userUri) {
		//TODO
	}
}
